package com.zhss.springbootdemo01.controller;

import com.zhss.springbootdemo01.domain.User;
import com.zhss.springbootdemo01.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.LogFactory;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2021/2/6 18:18
 * @Version 1.0
 */
@RestController
@RequestMapping(value="/user")
@Slf4j
public class UserController {

	@Autowired
 	private UserService userService;

	@GetMapping
	public List<User> listUsers() {
 		return userService.listUsers();
 	}

 	@GetMapping("/{userId}")
	public User getUser(@PathVariable("userId") Long userId) {
 		return userService.getUserById(userId);
	}

	@PostMapping
	public String saveUser(@RequestBody @Validated({User.Save.class}) User user, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			final List<ObjectError> allErrors = bindingResult.getAllErrors();
			final Optional<String> reduce = allErrors.stream().map(i -> i.getObjectName() + "," + i.getCode() + "," + i.getDefaultMessage() + ",").reduce(String::join);
			return reduce.orElse("异常.");
		}
		userService.saveUser(user);
		return "success";
	}

	@PutMapping("/{userId}")
	public String updateUser(@PathVariable("userId") Long userId,@RequestBody @Validated({User.Update.class}) User user) {
 		user.setId(userId);
 		userService.updateUser(user);
 		return "success";
   }

	@DeleteMapping("/{userId}")
	public String deleteUser(@PathVariable("userId") Long userId) {
		userService.removeUser(userId);
		return "success";
	}
}
